﻿using Sunny.UI;

namespace DataAcquisition
{
    public partial class RegistrationCodeForm : BaseForm
    {
        public RegistrationCodeForm()
        {
            InitializeComponent();
            Header.Text = "权限码";
        }

        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            if (RegistrationCodeInput.Text.IsNullOrEmpty())
            {
                Error("请输入权限码");
                return;
            }
            RegisterClass.WriteSetting("", "Code", RegistrationCodeInput.Text);
            ReloadInfo();
            this.Close();
        }

        private void RegistrationCodeForm_Load(object sender, EventArgs e)
        {
            ReloadInfo();
        }

        private void ReloadInfo()
        {
            RegistrationCodeInput.Text = RegisterClass.ReadSetting("", "Code", ""); ;

            string time = RegisterClass.StartTime();
            DateTime startDateTime = new DateTime();

            if (time.Length > 0)
            {
                long timestamp = time.ToLong(); // 时间戳

                DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
                startDateTime = dateTimeOffset.LocalDateTime;

                StartTimeInput.Text = startDateTime.ToString("yyyy-MM-dd HH:mm:ss");
            }

            DateTime endDateTime = new DateTime();
            time = RegisterClass.EndTime();
            if (time.Length > 0)
            {
                long timestamp = time.ToLong(); // 时间戳
                DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
                endDateTime = dateTimeOffset.LocalDateTime;

                EndTimeInput.Text = endDateTime.ToString("yyyy-MM-dd HH:mm:ss");
            }

            DateTime nowDateTime = DateTime.Now;
            int result1 = nowDateTime.CompareTo(startDateTime);
            int result2 = nowDateTime.CompareTo(endDateTime);
            if (result1 < 0)
            {
                StateInput.Text = "未生效";
            }
            else if (result2 > 0)
            {
                StateInput.Text = "已过期";
            }
            else if (result1 > 0 && result2 < 0)
            {
                StateInput.Text = "生效中";
            }
        }

        private void RegistrationCodeForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (this.Owner is not null)
            {
                ReportForm frm = (ReportForm)this.Owner;
                frm.ReloadEditAuthority();
            }
        }
    }
}
